<template>
    <el-dialog v-model="dialogFormVisible" :title="type ? '流程提交' : '流程审批'" draggable width="30%">
        <el-form :model="form" label-width="auto" :rules="rules" ref="ruleFormRef" v-loading="isLoading"
            element-loading-text="数据加载中...">
            <el-form-item label="下级审批人" prop="assigneeIds"
                v-if="form.approvalType === '0' && (form.currentNodeType === '0' || (form.currentNodeType !== '4' && form.approvalStatus === '1'))">
                <el-select clearable multiple v-model="form.assigneeIds" filterable placeholder="请选择下级审批人"
                    style="width: 200px">
                    <el-option v-for="item in assignees" :key="item.userId" :label="item.username"
                        :value="item.userId" />
                </el-select>
            </el-form-item>
            <el-form-item :label="form.approvalStatus === '5' ? '转办人：' : '加签人：'" prop="assigneeIds"
                v-if="form.approvalStatus === '5' || form.approvalStatus === '6'">
                <user-select :placeholder="form.approvalStatus === '5' ? '请选择转办人' : '请选择加签人'" :max="10"
                    @submit="selectAssignee"></user-select>
            </el-form-item>
            <el-form-item label="审批状态" v-if="!type" prop="approvalStatus">
                <el-tag type="success" v-if="form.approvalStatus === '1'">同意</el-tag>
                <el-tag type="danger" v-else-if="form.approvalStatus === '2'">拒绝</el-tag>
                <el-tag type="warning" v-else-if="form.approvalStatus === '3'">退回</el-tag>
                <el-tag type="primary" v-else-if="form.approvalStatus === '5'">转办</el-tag>
                <el-tag type="info" v-else-if="form.approvalStatus === '6'">加签</el-tag>
            </el-form-item>
            <el-form-item label="审批意见" prop="remark" style="width: 100%;" v-if="!type && form.approvalStatus !== '6'">
                <el-input type="textarea" v-model="form.remark" placeholder="请输入审批意见" />
            </el-form-item>
            <el-form-item label="抄送(非必选)" prop="ccTo" v-if="form.approvalStatus !== '5' && form.approvalStatus !== '6'">
                <div>
                    <el-tag v-for="tag in ccToTags" :key="tag" closable :disable-transitions="false"
                        @close="closeTag(tag)" style="margin-right: 5px;">
                        {{ tag.username }}
                    </el-tag>
                    <el-select ref="ccToSelectRef" v-if="ccToSelectVisible" v-model="selectCcTo" filterable remote
                        reserve-keyword placeholder="搜索抄送人" remote-show-suffix :remote-method="getCcToOptions"
                        size="small" style="width: 100px" value-key="userId" @change="changeCcTo"
                        @blur="ccToSelectVisible = false">
                        <el-option v-for="item in ccToOptions" :key="item.userId" :label="item.username"
                            :value="item" />
                    </el-select>
                    <el-button v-else size="small" @click="showCcToSelect">
                        + 添加
                    </el-button>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">返回</el-button>
                <el-button type="primary" :disabled="isLoading" @click="submit">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, nextTick } from "vue";
import { ElMessage } from 'element-plus'
import api from "@/api"
import userSelect from "@/components/user-select.vue";

const isLoading = ref(false)
const dialogFormVisible = ref(false)
const assignees = ref([])
const form = ref({})
const type = ref(true)//true-start，false-commit
const ccToSelectVisible = ref(false)
const ccToTags = ref([])
const ccToOptions = ref([])
const selectCcTo = ref()
const ccToSelectRef = ref(null)
const ruleFormRef = ref()
const rules = ref({
    assigneeIds: [
        { required: true, message: '请选择审批人', trigger: 'blur' }
    ],
    approvalStatus: [
        { required: true, message: '请选择审批状态', trigger: 'blur' }
    ],
    remark: [
        { required: true, message: '请输入审批意见', trigger: 'blur' }
    ]
})

const showCcToSelect = async () => {
    ccToSelectVisible.value = true
    await getCcToOptions()
    await nextTick()
    if (ccToSelectRef.value) {
        ccToSelectRef.value.focus();
    }
}

const getCcToOptions = async (keywork) => {
    if (keywork || ccToOptions.value.length === 0) {
        const res = await api.get('/author/user/pageList', { username: keywork, status: '0' })
        if (res.data.code === 200) {
            const users = res.data.data.records.map(item => ({ userId: item.userId, username: item.username }))
            ccToOptions.value = users
        } else {
            ElMessage.error(res.data.msg)
        }
    }
}

const changeCcTo = (value) => {
    if (value) {
        const index = ccToTags.value.findIndex(item => item.userId === value.userId);
        if (index > -1) {
            selectCcTo.value = null
            ElMessage.warning(value.username + '已存在！')
            return
        }
        ccToTags.value.push(value)
    }
    ccToSelectVisible.value = false
    selectCcTo.value = null
}

const closeTag = (tag) => {
    const index = ccToTags.value.findIndex(item => item.userId === tag.userId);
    if (index > -1) {
        ccToTags.value.splice(index, 1)
    }
}

//初始组件satrt
const initStart = async (definitionId, instanceId, data) => {
    isLoading.value = true
    dialogFormVisible.value = true
    type.value = true
    ccToTags.value = []
    form.value = {}
    form.value.data = data
    form.value.instanceId = instanceId
    const res = await api.post('/workflow/init', { definitionId, data })
    if (res.data.code === 200) {
        const data = res.data.data
        assignees.value = data.assignees
        if (data.approvalType === '1') {
            form.value.assigneeIds = data.assignees.map(item => item.userId)
        }
        form.value.definitionId = data.definitionId
        form.value.nextNodeId = data.nextNodeId
        form.value.currentNodeType = data.currentNodeType
        form.value.approvalType = data.approvalType
    } else {
        ElMessage.error(res.data.msg)
    }
    isLoading.value = false

}

//初始组件commit
const initCommit = async (taskId, instanceId, approvalStatus, data) => {
    isLoading.value = true
    dialogFormVisible.value = true
    type.value = false
    ccToTags.value = []
    form.value = {}
    form.value.approvalStatus = approvalStatus
    form.value.taskId = taskId
    form.value.data = data
    const res = await api.post('/workflow/init', { instanceId })
    if (res.data.code === 200) {
        const data = res.data.data
        assignees.value = data.assignees
        form.value.nextNodeId = data.nextNodeId
        form.value.currentNodeId = data.currentNodeId
        form.value.instanceId = data.instanceId
        form.value.currentNodeType = data.currentNodeType
        form.value.approvalType = data.approvalType
        if (data.approvalType === '1') {
            form.value.assigneeIds = data.assignees.map(item => item.userId)
        }
    } else {
        ElMessage.error(res.data.msg)
    }
    isLoading.value = false
}

const selectAssignee = (val) => {
    form.value.assigneeIds = val.haveSelect.map(item => item.userId)
}

const emit = defineEmits(['serversUpdated']);
const submit = () => {
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            isLoading.value = true
            let url
            if (type.value) {
                url = '/workflow/start'
            } else {
                url = '/workflow/commit'
            }
            if (ccToTags.value.length > 0) {
                const ccToIds = ccToTags.value.map(item => item.userId)
                form.value.ccToIds = ccToIds
            }
            const res = await api.post(url, form.value)
            if (res.data.code === 200) {
                ElMessage.success(res.data.msg)
                emit('serversUpdated')
                dialogFormVisible.value = false
            } else {
                ElMessage.error(res.data.msg)
            }
            isLoading.value = false
        }
    })
}
defineExpose({
    initStart,
    initCommit
});
</script>
<style lang="less" scoped></style>